1. MongoDB Update Operations

Definition

MongoDB update operations modify existing documents in a collection. The update operations provide various methods to update document fields, including setting new values, incrementing values, updating arrays, and performing complex updates using operators.

Algorithm 1: Basic Document Update :-
  • Step 1: Select the collection
  • Step 2: Specify update criteria
  • Step 3: Choose update operator
  • Step 4: Define update values
  • Step 5: Execute update operation
  • Example 1: Basic Field Update
    // Update student grade
    db.students.updateOne(
    { name: "John Doe" },
    {
    $set: {
    grade: "A",
    lastUpdated: new Date()
    }
    }
    )
    Algorithm 2: Array Update Operations :-
  • Step 1: Identify array field
  • Step 2: Choose array update operator
  • Step 3: Specify array elements
  • Step 4: Define update conditions
  • Step 5: Execute array update
  • Example 2: Array Update
    // Update array elements
    db.users.updateOne(
    { _id: ObjectId("123") },
    {
    $push: {
    hobbies: "reading"
    },
    $pull: {
    oldHobbies: "gaming"
    }
    }
    )
    Algorithm 3: Multiple Document Update :-
  • Step 1: Define update criteria
  • Step 2: Prepare update operations
  • Step 3: Set update options
  • Step 4: Apply bulk updates
  • Step 5: Verify results
  • Example 3: Multiple Document Update
    // Update multiple documents
    db.products.updateMany(
    { category: "electronics" },
    {
    $inc: { price: 10 },
    $set: {
    updated: true,
    lastModified: new Date()
    }
    }
    )